package com.dolphin.aiagentplatform.utils;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;

import java.security.SecureRandom;
import java.util.UUID;

/**
 * 安全工具类，提供密码加密、随机密钥生成等安全相关功能
 */
public class SecurityUtils {

    /**
     * 默认盐值
     */
    @Value(value = "{dolphin.salt}")
    private static String DEFAULT_SALT;

    /**
     * MD5加密
     */
    public static String encryptPassword(String password) {
        return encryptPassword(password, DEFAULT_SALT);
    }

    /**
     * MD5加密（指定salt）
     */
    public static String encryptPassword(String password, String salt) {
        if (password == null) {
            throw new IllegalArgumentException("密码不能为空");
        }
        return DigestUtils.md5DigestAsHex((salt + password).getBytes());
    }

    /**
     * 验证密码是否匹配
     */
    public static boolean matchPassword(String originalPassword, String encodedPassword) {
        if (originalPassword == null || encodedPassword == null) {
            return false;
        }
        return encryptPassword(originalPassword).equals(encodedPassword);
    }

    /**
     * 生成随机盐值
     */
    public static String generateSalt() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 生成以字母开头、包含数字和字母的随机用户名
     */
    public static String generateRandomUsername(int length) {
        if (length < 4) {
            throw new IllegalArgumentException("用户名长度不能小于4");
        }

        SecureRandom random = new SecureRandom();
        String letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
        String alphanumeric = letters + "0123456789";

        StringBuilder sb = new StringBuilder(length);
        // 第一个字符必须是字母
        sb.append(letters.charAt(random.nextInt(letters.length())));

        // 剩余字符可以是字母或数字
        for (int i = 1; i < length; i++) {
            sb.append(alphanumeric.charAt(random.nextInt(alphanumeric.length())));
        }

        return sb.toString();
    }

    /**
     * 获取客户端真实IP地址
     */
    public static String getClientIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");

        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        // 如果是多级代理，取第一个IP地址
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0].trim();
        }

        return ip;
    }
} 